package com.lingxu.module.earlyWarn.service.impl;

import cn.afterturn.easypoi.excel.entity.params.ExcelExportEntity;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lingxu.base.common.api.vo.Result;
import com.lingxu.base.common.util.EasyExcelUtils;
import com.lingxu.base.common.util.FileUtils;
import com.lingxu.base.common.util.UUID32Generator;
import com.lingxu.base.common.util.ZipUtils;
import com.lingxu.base.system.fileManage.entity.SysFileInfo;
import com.lingxu.base.system.fileManage.mapper.SysFileInfoMapper;
import com.lingxu.module.collection.entity.ModelColumnInfo;
import com.lingxu.module.collection.entity.ModelRunRecord;
import com.lingxu.module.collection.entity.ReportDetail;
import com.lingxu.module.collection.mapper.ReportMapper;
import com.lingxu.module.earlyWarn.entity.ApprovalList;
import com.lingxu.module.earlyWarn.entity.IssueManage;
import com.lingxu.module.earlyWarn.entity.IssueManageBook;
import com.lingxu.module.earlyWarn.entity.IssueParams;
import com.lingxu.module.earlyWarn.mapper.IssueManageBookMapper;
import com.lingxu.module.earlyWarn.mapper.IssueManageMapper;
import com.lingxu.module.earlyWarn.mapper.ModelIssueCaredMapper;
import com.lingxu.module.earlyWarn.service.IssueManageSercvice;
import com.lingxu.module.earlyWarn.vo.AreaTree;
import com.lingxu.module.redList.entity.RedList;
import com.lingxu.module.redList.mapper.RedListMapper;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Title: IssueManageServiceImpl
 * @Package: com.lingxu.module.earlyWarn.service.impl
 * @Author: ysj闫世杰
 * @Email: 1105324813@qq.com
 * @Date: Created in 2024/1/3 15:09
 * @Description:
 * @Version: 1.0.0
 */
@Service
public class IssueManageServiceImpl extends ServiceImpl<IssueManageMapper, IssueManage>
        implements IssueManageSercvice {

    @Value(value = "${uploadUrl}")
    private String uploadpath;
    @Autowired
    private SysFileInfoMapper sysFileInfoMapper;
    @Autowired
    private IssueManageMapper issueManageMapper;
    @Autowired
    private IssueManageBookMapper issueManageBookMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private RedListMapper redListMapper;
    @Autowired
    private ModelIssueCaredMapper modelIssueCaredMapper;

    @Override
    @Transactional
    public Result addIssueHandle(IssueManage issueManage) {
//        if(!"1".equals(issueManage.getIsLeader())){
//            issueManage.setDisposalStatus("待处置");
//        }
//       else {
//           issueManage.setApprovalStatus("0");
//           issueManage.setDisposalStatus("待审核");
//       }

         issueManage.setApprovalStatus("1");
         issueManage.setDisposalStatus("处置中");

        //是否疑点问题
        issueManage.setIsDoubtData("是");
        //推送部门绑定为建议办理部门
        issueManage.setSuggestionDept(issueManage.getPushDept());
        issueManage.setSuggestionDeptName(issueManage.getPushDeptName());
        issueManage.setHandleType(issueManage.getHandleType());
        issueManageMapper.updateById(issueManage);
        if(issueManage.getFileInfoList() != null && issueManage.getFileInfoList().size() > 0){
            for(SysFileInfo info : issueManage.getFileInfoList()){
                info.setId(UUID32Generator.generate());
                info.setRecordId(issueManage.getId());
                info.setTableName("1"); //新增办理文件类型
                sysFileInfoMapper.insert(info);
            }
        }
        return Result.ok("操作成功");
    }


    /**
     * @Author ysj闫世杰
     * @Description 查询江苏省区划
     * @Date 2024/1/4 10:07
     * @Param:
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findRegionTree() {
        try {
            List<AreaTree> areaTrees = issueManageMapper.findRegionTree();
            return Result.ok(buildTreeList(areaTrees,"0"),"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 查询已添加、未添加标签
     * @Date 2024/1/4 11:24
     * @Param: issueId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findTagInAndOut(String issueId) {
        try {
            Map<String,Object> map = new HashMap<>();
            //查询已维护标签值
            IssueManage manage = issueManageMapper.selectById(issueId);
            List<String> inTagList = new ArrayList<>();
            if(!StringUtils.isEmpty(manage.getIssueTag())){
                inTagList = Arrays.asList(manage.getIssueTag().split(","));
            }
            //查询全部标签值
            List<String> allTagList = issueManageMapper.findAllTagList();
            //取差集
            List<String> finalInTagList = inTagList;
            List<String> outTagList = allTagList.stream().filter(item -> !finalInTagList.contains(item)).collect(Collectors.toList());
            map.put("inTagList",inTagList);
            map.put("outTagList",outTagList);
            return Result.ok(map,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 批量转办
     * @Date 2024/1/5 15:02
     * @Param: params
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result issueTransferBatch(IssueParams params) {
        try {
            for(String id : params.getIds()){
                IssueManage issueManage = new IssueManage();
                issueManage.setId(id);
                issueManage.setIsDoubtData("是");
                issueManage.setDisposalStatus("待处置");
                issueManage.setPushDate(new Date());
                issueManage.setSuggestionDept(params.getSuggestionDept());
                issueManage.setSuggestionDeptName(params.getSuggestionDeptName());
                issueManageMapper.updateById(issueManage);
                if(params.getFileInfoList() != null){
                    for(SysFileInfo info : params.getFileInfoList()){
                        info.setId(UUID32Generator.generate());
                        info.setRecordId(issueManage.getId());
                        info.setTableName("2"); //批量转办文件类型
                        sysFileInfoMapper.insert(info);
                    }
                }
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * 拆分问题之后的转办操作
     * @param params
     * @return
     */
    @Override
    @Transactional
    public Result issueTransfer(IssueParams params) {
        try {
            if("0".equals(params.getSfcfzb())){//拆分
                StringBuffer stringBuffer = new StringBuffer();
                IssueManage manage = issueManageMapper.selectById(params.getIds().get(0));
                for(Map map : params.getTransferDeptList()){//多个转办地区编码和名称
                    String id = UUID32Generator.generate();
                    manage.setId(id);
                    manage.setIsDoubtData("是");
                    manage.setDisposalStatus("待处置");
                    manage.setPushDate(new Date());
                    manage.setSuggestionDept(map.get("suggestiondept").toString());
                    manage.setSuggestionDeptName(map.get("suggestiondeptname").toString());
                    manage.setSfcfzb("0");
                    manage.setCfzbzid(params.getIds().get(0));
                    manage.setZbssdq(map.get("zbssdq").toString());
                    issueManageMapper.insert(manage);
                    //拆分插入关注列表
                    if(StringUtils.isNotBlank(params.getCared()) && "1".equals(params.getCared())){
                        modelIssueCaredMapper.deleteModelIssueCared(id, params.getLoginUserId());
                        modelIssueCaredMapper.addModelIssueCared(id, params.getLoginUserId());
                    }

                    stringBuffer.append(id+",");
                }
                IssueManage issueManage = new IssueManage();
                issueManage.setId(params.getIds().get(0));
                issueManage.setSfcfzb("2");
                issueManage.setCfzbids(stringBuffer.substring(0,stringBuffer.length() - 1));
                issueManageMapper.updateById(issueManage);
            } else {
                for(String id : params.getIds()){
                    IssueManage issueManage = new IssueManage();
                    issueManage.setId(id);
                    issueManage.setIsDoubtData("是");
                    issueManage.setSfcfzb("1");
                    issueManage.setDisposalStatus("待处置");
                    issueManage.setPushDate(new Date());
                    issueManage.setSuggestionDept(params.getSuggestionDept());
                    issueManage.setSuggestionDeptName(params.getSuggestionDeptName());
                    issueManageMapper.updateById(issueManage);
                    if(params.getFileInfoList() != null){
                        for(SysFileInfo info : params.getFileInfoList()){
                            info.setId(UUID32Generator.generate());
                            info.setRecordId(issueManage.getId());
                            info.setTableName("2"); //批量转办文件类型
                            sysFileInfoMapper.insert(info);
                        }
                    }
                }
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 核查列表
     * @Date 2024/1/5 16:35
     * @Param: params
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findIssueCheckedList(IssueParams params) {
        try {
            if(params.getRegion().endsWith("00")){
                params.setRegion(null);
            }
            Page<IssueManage> managePage = new Page<>(params.getPage(),params.getLimit());
            IPage<IssueManage> list = issueManageMapper.findIssueCheckedList(params,managePage);
            return Result.ok(list,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 核查办理··
     * @Date 2024/1/8 9:16
     * @Param: manage
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result issueCheckedHandler(IssueManage manage) {
        try {
            manage.setCheckdStatus("已核查");
            manage.setDisposalStatus("已处置");
            //处置登记时间
            manage.setCheckedTime(new Date());
            //核查办理已申请
            manage.setCheckedApprovalStatus("0");
            issueManageMapper.updateById(manage);
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 上传审批单·
     * @Date 2024/1/8 9:45
     * @Param: manage
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result uploadApprovalOrder(IssueManage manage) {
        try {
            for(SysFileInfo fileInfo : manage.getFileInfoList()){
                fileInfo.setTableName("3");  //审批单文件类型
                fileInfo.setRecordId(manage.getId());
                fileInfo.setId(UUID32Generator.generate());
                sysFileInfoMapper.insert(fileInfo);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     *
     * 上传典型案例附件
     * @param manage
     * @return
     */
    @Override
    public Result uploadTypicalCasesAnnex(IssueManage manage) {
        try {
            for(SysFileInfo fileInfo : manage.getFileInfoList()){
                fileInfo.setTableName("4");  //典型案例附件类型
                fileInfo.setRecordId(manage.getId());
                fileInfo.setId(UUID32Generator.generate());
                sysFileInfoMapper.insert(fileInfo);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询需要领导审批的问题办理
     * @Date 2024/1/8 11:00
     * @Param: params
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findIssueHandleNeedApproval(IssueParams params) {
        try {
            if(params.getRegion().endsWith("00")){
                params.setRegion(null);
            }
            Page<ApprovalList> managePage = new Page<>(params.getPage(),params.getLimit());
            IPage<ApprovalList> list = issueManageMapper.findIssueHandleNeedApproval(params,managePage);
            return Result.ok(list,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 领导审批
     * @Date 2024/1/8 16:20
     * @Param: manage
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result leaderApproval(IssueManage manage) {
        try {
            //办理审批
            if(manage.getApprovalTime() != null){
                manage.setApprovalTime(new Date());
                if("1".equals(manage.getApprovalStatus())){
                    manage.setDisposalStatus("待处置");
                }
            }
            //核查审批未通过返回上一节点
//            if(manage.getCheckedApprovalTime() != null){
//                manage.setCheckedApprovalTime(new Date());
//                if(!"1".equals(manage.getCheckedApprovalStatus())){
//                    manage.setDisposalStatus("待接收");
//                }
//            }
            issueManageMapper.updateById(manage);
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 下级退回
     * @Date 2024/1/8 16:20
     * @Param: manage
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result subordinateBack(IssueManage manage) {
        return null;
    }


    /**
     * @Author ysj闫世杰
     * @Description 办理结果
     * @Date 2024/1/8 16:32
     * @Param: manage
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result updateIssueResults(IssueManage manage) {
        try {
//            manage.setDisposalStatus("已办结");
            manage.setLastResultTime(new Date());
            issueManageMapper.updateById(manage);
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 办结批量
     * @Date 2024/1/10 9:29
     * @Param: params
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result updateIssueOverBatch(IssueParams params) {
        try {
            for(String s : params.getIds()){
                IssueManage manage = new IssueManage();
                manage.setId(s);
                manage.setDisposalStatus("已处置");
                manage.setIssueDoneOpinion(params.getIssueDoneOpinion());
                issueManageMapper.updateById(manage);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }



    /**
     * @Author ysj闫世杰
     * @Description 查询审批单
     * @Date 2024/1/9 11:29
     * @Param: id
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findApprovalOrder(String id) {
        try {
            Map<String,Object> map = new HashMap<>(4);
            map.put("RECORD_ID",id);
            List<SysFileInfo> fileInfos = sysFileInfoMapper.selectByMap(map);
            return Result.ok(fileInfos,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 统计已审批、未审批数量
     * @Date 2024/1/9 14:52
     * @Param: params
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findIssueHandleNeedApprovalCount(IssueParams params) {
        try {
            if(params.getRegion().endsWith("00")){
                params.setRegion(null);
            }
            int ysp = issueManageMapper.findIssueHandleNeedApprovalCount(params,"1");
            int wsp = issueManageMapper.findIssueHandleNeedApprovalCount(params,"0");
            Map<String, Integer> map = new HashMap<>();
            map.put("ysp",ysp);
            map.put("wsp",wsp);
            return Result.ok(map,"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }


    /**
     * @Author ysj闫世杰
     * @Description 保存审批单数据
     * @Date 2024/1/12 11:43
     * @Param: manageBook
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result saveApprovalOrder(IssueManageBook manageBook) {
        try {
            //先更新表，否则新增
            UpdateWrapper<IssueManageBook> wrapper = new UpdateWrapper<>();
            wrapper.eq("MANAGE_ID",manageBook.getManageId());
            int row = issueManageBookMapper.update(manageBook,wrapper);
            if(row < 1){
                //新增
                issueManageBookMapper.insert(manageBook);
            }
            return Result.ok("操作成功");
        }catch (Exception e){
            log.error("操作异常",e);
            return Result.error("操作异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 查询审批单数据
     * @Date 2024/1/12 11:43
     * @Param: manageId
     * @return com.lingxu.base.common.api.vo.Result
     **/
    @Override
    public Result findApprovalOrderData(String manageId) {
        try {
            Map<String,Object> map = new HashMap<>();
            map.put("MANAGE_ID",manageId);
            return Result.ok(issueManageBookMapper.selectByMap(map),"查询成功");
        }catch (Exception e){
            log.error("数据查询异常",e);
            return Result.error("查询异常");
        }
    }

    /**
     * @Author ysj闫世杰
     * @Description 导出Excel问题数量
     * @Date 2024/1/4 17:41
     * @Param: modelIds
     * @Param: response
     * @return void
     **/
    @Override
    public void exportExcelFile(String modelId, String issueId, HttpServletResponse response) {
        try {
            String filePath = uploadpath + "/excel/";
            File exists = new File(filePath);
            if(!exists.exists()){
                exists.mkdirs();
            }
            List<File> fileList = new ArrayList<>();
            //查询其下所有模型详情信息
            ReportDetail detail = reportMapper.findModelDetail(modelId);
            //查询预警核查问题详情
            IssueManage manage = issueManageMapper.selectById(issueId);
            List<Map> runidList = JSONUtil.toList(manage.getRunid().toString(), Map.class);
            //子模型id合集
            String[] ids = detail.getLinkmodelid().split(",");
            for(String id : ids) {
                //获取运行的详细信息
                ModelRunRecord modelRunRecord = reportMapper.getModelRunRecordByModelIdAndRunId(id, getRunIdByModelId(runidList, id));
                if (modelRunRecord == null) {
                    continue;
                }
                //查询单个模型基本信息
                ReportDetail modelDetail = reportMapper.findModelDetail(id);
                String resulttable = modelRunRecord.getResulttable();
                String resultcolumns = modelRunRecord.getResultcolumns();
                List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultcolumns, ModelColumnInfo.class);
                Map<String, String> head = new LinkedHashMap<>();
                if (modelColumnInfoList.size() > 0) {
                    for (ModelColumnInfo modelColumnInfo : modelColumnInfoList) {
                        head.put(modelColumnInfo.getEnname(), modelColumnInfo.getCnname());
                    }
                    String[] objects = head.keySet().toArray(new String[0]);
                    List<String> list = new ArrayList<>(Arrays.asList(objects));
                    String columns = org.apache.commons.lang3.StringUtils.join(list, ",");
                    //根据拆分所属区域,获取相关数据
                    String sql = "";
                    String sssjly = getSssjlyByRunId(runidList,getRunIdByModelId(runidList, id));
                    if("0".equals(manage.getSfcfzb()) && !"其他".equals(manage.getZbssdq()) && StringUtils.isNotBlank(sssjly)){
                        sql = "select " + columns + ", '否' as ISRED" + " from DIMENRESULT." + resulttable +" WHERE "+sssjly+" = '"+manage.getZbssdq()+"'";
                    }else{
                        sql = "select " + columns + ", '否' as ISRED" + " from DIMENRESULT." + resulttable;
                    }

                    //新增默认字段是否红名单
                    head.put("ISRED","是否红名单");
                    List<LinkedHashMap<String, Object>> dataList = reportMapper.getResultList(sql);
                    //用户存放红名单人员信息
                    List<LinkedHashMap<String, Object>> contain = new ArrayList<>();
                    //查询红名单
                    List<RedList> redLists = redListMapper.openFindRedListApi(null);
                    //遍历去除红名单数据
                    Iterator<LinkedHashMap<String, Object>> iterator = dataList.iterator();
                    while (iterator.hasNext()) {
                        LinkedHashMap<String, Object> m = iterator.next();
                        for (String keys : m.keySet()) {
                            if (keys.contains("SFZ") || keys.contains("ZJHM")) {
                                String values = (String) m.get(keys);
                                for (RedList red : redLists) {
                                    String idcard = red.getIdcard();
                                    if (idcard.equals(values)) {
                                        //放入红名单人员list
                                        contain.add(m);
                                        iterator.remove();
                                        System.out.println("过滤红名单数据：" + idcard);
                                        break;
                                    }
                                }
                                break;
                            }
                        }
                    }

                    //判断是否通过红名单人员查看权限
                    String redtotal = modelRunRecord.getRedtotal();
                    if(!org.apache.commons.lang3.StringUtils.isEmpty(redtotal)){
                        int red = Integer.parseInt(redtotal);
                        String state = modelRunRecord.getApprovestate();
                        //红名单人员数量大于0并且通过审批
                        if(red > 0 && "1".equals(state)){
                            for(LinkedHashMap<String, Object> m : contain){
                                m.put("ISRED","是");
                            }
                            dataList.addAll(contain);
                        }
                    }
                    if(dataList.size() > 0){
                        //保存Excel文件
                        String excelFileName = filePath + modelDetail.getModel()+ ".xls";
                        saveExcel(dataList, head, excelFileName);
                        File file = new File(excelFileName);
                        fileList.add(file);
                    }
                }
            }
            if(fileList.size() > 0){
                //打包成zip
                String zipName = filePath + detail.getMastermodelname() + ".zip";
                OutputStream outputStream = new FileOutputStream(zipName);
                ZipUtils.toZip(fileList,outputStream);
                //下载文件
                FileUtils.downloaddocx(zipName,response, false);
                //删除文件
                File zip = new File(zipName);
                zip.delete();
                for(File f : fileList){
                    f.delete();
                }
            }
        }catch (Exception e){
            log.error("操作异常",e);
        }
    }

    //获取当前模型id所属的问题运行id
    private static String getRunIdByModelId(List<Map> runidList, String modelId) {
        String runid = "" ;
        for (Map runidMap : runidList) {
            Iterator<Map.Entry<String, Object>> it = runidMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                if(entry.getKey().equals(modelId)){
                    runid = entry.getValue().toString();
                    break;
                }
            }
        }
        return runid;
    }

    //获取当前运行id所属的sssjly  所属数据来源字段名
    private static String getSssjlyByRunId(List<Map> runidList, String runId) {
        String sssjly = "" ;
        for (Map runidMap : runidList) {
            Iterator<Map.Entry<String, Object>> it = runidMap.entrySet().iterator();
            while(it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                if(entry.getKey().equals(runId)){
                    sssjly = entry.getValue().toString();
                    break;
                }
            }
        }
        return sssjly;
    }

    //处理转办多部门数据统计
    public List<LinkedHashMap<String, Object>> getDatalist(String modelId) {
        List<LinkedHashMap<String, Object>> data = new ArrayList<>();
        //查询其下所有模型运行记录结果
        ReportDetail detail = reportMapper.findModelDetail(modelId);
        //子模型id合集
        String[] ids = detail.getLinkmodelid().split(",");
        for(String id : ids) {
            ModelRunRecord modelRunRecord = reportMapper.getModelRunRecordByModelId(id);
            if (modelRunRecord == null) {
                continue;
            }
            //查询单个模型基本信息
            ReportDetail modelDetail = reportMapper.findModelDetail(id);
            String resulttable = modelRunRecord.getResulttable();
            String resultcolumns = modelRunRecord.getResultcolumns();
            List<ModelColumnInfo> modelColumnInfoList = JSON.parseArray(resultcolumns, ModelColumnInfo.class);
            Map<String, String> head = new LinkedHashMap<>();
            if (modelColumnInfoList.size() > 0) {
                for (ModelColumnInfo modelColumnInfo : modelColumnInfoList) {
                    head.put(modelColumnInfo.getEnname(), modelColumnInfo.getCnname());
                }
                String[] objects = head.keySet().toArray(new String[0]);
                List<String> list = new ArrayList<>(Arrays.asList(objects));
                String columns = org.apache.commons.lang3.StringUtils.join(list, ",");
                String sql = "select " + columns + " from DIMENRESULT." + resulttable;
                List<LinkedHashMap<String, Object>> dataList = reportMapper.getResultList(sql);

                data.addAll(dataList);
            }
        }
        //处理数据

        return null;
    }

    //保存Excel
    private void saveExcel(List<LinkedHashMap<String,Object>> dataAll,Map<String,String> headMap,String fileName){
        //要导出的动态列
        List<ExcelExportEntity> beanList = new ArrayList<>();
        for(Map.Entry<String,String> map : headMap.entrySet()){
            beanList.add(new ExcelExportEntity(map.getValue(),map.getKey().toUpperCase()));
        }
        EasyExcelUtils.writeExcelToStream(fileName,beanList,dataAll);
    }



    //处理行政区划树
    private static List<AreaTree> buildTreeList(List<AreaTree> treeList, String ids){
        //获取parentId的根节点
        List<AreaTree> areaTrees = treeList.stream().filter(item -> item.getPid().equals(ids)).collect(Collectors.toList());
        //根据parentId进行分组
        Map<String,List<AreaTree>> map = treeList.stream().collect(Collectors.groupingBy(AreaTree::getPid));
        recursionFnTree(areaTrees,map);
        return areaTrees;
    }

    private static void recursionFnTree(List<AreaTree> areaTrees,Map<String,List<AreaTree>> map){
        for(AreaTree areaTree : areaTrees){
            List<AreaTree> childList = map.get(areaTree.getId());
            areaTree.setTreeList(childList);
            if (null != childList && 0 < childList.size()){
                recursionFnTree(childList,map);
            }else {
                areaTree.setTreeList(new ArrayList<>());
            }
        }
    }

    //问题转办页面，问题拆分
    @Override
    public Result issueSplitBySssjly(String modelId, String issueId) {
        List<Map> resultList = new ArrayList<>();
        Map<Object, Long> sjlyMap = new HashMap<Object, Long>();
        Map<String, Object> sjlyXqMap = new HashMap<String, Object>();
        //查询预警核查问题详情
        IssueManage manage = issueManageMapper.selectById(issueId);
        List<Map> runidList = JSONUtil.toList(manage.getRunid().toString(), Map.class);
        //查询其下所有模型详情信息
        ReportDetail detail = reportMapper.findModelDetail(modelId);
        //子模型id合集
        String[] ids = detail.getLinkmodelid().split(",");
        for(String id : ids) {
            String runId = getRunIdByModelId(runidList, id);
            if(StringUtils.isBlank(runId)) {
                continue;
            }

            ModelRunRecord modelRunRecord = reportMapper.getModelRunRecordByModelIdAndRunId(id, runId);
            //获取所属数据来源字段信息
            String sssjly = getSssjlyByRunId(runidList, runId);
            String sql = "";
            Map<Object, Long> countMap = new HashMap<>();
            if(StringUtils.isBlank(sssjly)){
                sql = "select count(*) from DIMENRESULT." + modelRunRecord.getResulttable();
                Integer dataListCount = reportMapper.getResultCount(sql);
                countMap.put("其他", Long.valueOf(dataListCount));
            } else {
                sql = "select " + sssjly + " as sssjly from DIMENRESULT." + modelRunRecord.getResulttable();
                List<LinkedHashMap<String, Object>> dataList = reportMapper.getResultList(sql);
                countMap = dataList.stream().collect(Collectors.groupingBy(item -> {return item.get("SSSJLY");}, Collectors.counting()));
            }

            //合并所属相同属地的数量
            countMap.forEach((k, v) -> sjlyMap.merge(k, v, Long::sum));
            sjlyXqMap.put(modelRunRecord.getName(),countMap);
        }

        //循环获取子集中的数据
        Map<String, Object> sjlyBySonSum = new HashMap<>();
        sjlyMap.forEach((k,v) ->{
            Iterator<Map.Entry<String, Object>> it = sjlyXqMap.entrySet().iterator();
            List<Map<String,Object>> sjlyBySonModelList = new ArrayList<>();
            while(it.hasNext()){
                Map.Entry<String, Object> entry = it.next();
                Map<String, Object> sjlyBySonModel = new HashMap<>();
                Map<Object, Long> sonCountMap = (Map<Object, Long>) entry.getValue();
                if(sonCountMap.get(k) != null){
                    sjlyBySonModel.put(entry.getKey(),sonCountMap.get(k));
                    sjlyBySonModelList.add(sjlyBySonModel);
                }
            }
            sjlyBySonSum.put(k.toString(),sjlyBySonModelList);
        });

        //拼装数据返回结构
        sjlyMap.forEach((k,v) ->{
            Map<String,Object> dataMap = new HashMap<>();
            dataMap.put(k.toString(),v);
            dataMap.put("wtlb",sjlyBySonSum.get(k));
            resultList.add(dataMap);
        });

        return Result.ok(resultList,"查询成功");
    }

    @Override
    public Result getHaveTableListByModelId(String modelId) {
        return Result.ok(issueManageMapper.getHaveTableListByModelId(modelId),"查询成功");
    }

    @Override
    public Result deleteIssueManageByModelId(String modelId) {
        return Result.ok(issueManageMapper.deleteIssueManageByModelId(modelId),"删除成功");
    }
}
